package com.ln.spring4X.configAndComponent;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.util.stream.Stream;

@ComponentScan(basePackageClasses = ConfigurationAndComponentMain.class)
public class ConfigurationAndComponentMain {

    public static void main(String[] args) {
        // 构建 Annotation 配置驱动 Spring 上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册 配置Bean SpringContextConfiguration 到 Spring 上下文
        context.register(HumanConfiguration.class);
        context.register(HumanComponent.class);
        // 启动上下文
        context.refresh();

//        // 输出当前 Spring 应用上下文中所有注册的 Bean 名称
//        System.out.println("当前 Spring 应用上下文中所有注册的 Bean 名称：");
//        Stream.of(context.getBeanDefinitionNames())
//                .map(name -> "\t" + name) // 增加格式缩进
//                .forEach(System.out::println);
        
        // configuration 中的情况
        System.out.println("configuration: ");
        Child childByConfiguration = context.getBean("getChildByConfiguration", Child.class);
        System.out.printf("child: %s \n", childByConfiguration);
        Woman womanByConfiguration = context.getBean("getWomanByConfiguration", Woman.class);
        System.out.printf("woman: %s \n", womanByConfiguration);
        System.out.printf("woman child: %s \n", womanByConfiguration.getChild());
        System.out.printf("woman child = child? : %s \n", womanByConfiguration.getChild() == childByConfiguration);

        // component 中的情况
        System.out.println("component: ");
        Child childByComponent = context.getBean("getChildByComponent", Child.class);
        System.out.printf("child: %s \n", childByComponent);
        Woman womanByComponent = context.getBean("getWomanByComponent", Woman.class);
        System.out.printf("woman: %s \n", womanByComponent);
        System.out.printf("woman child: %s \n", womanByComponent.getChild());
        System.out.printf("woman child = child? : %s \n", womanByComponent.getChild() == childByComponent);
        
        // 关闭上下文
        context.close();
    }

}
